//index.js
//获取应用实例
var WXGrid = require('../../utils/wxgrid.js')
var bibleData = require('../../utils/bible.js')
var glo = require('../../utils/global.js')
var config = require('../../utils/config.js')
var app = getApp();
var lastTapDiffTime = 0;
var bibleMsg = {
    bookId: '',
    bookName: '',
    chapterCount: '',
    chapterId: '',
    verseId: ''

};


function _goContent(obj) {
    var content = "";
    wx.getStorage({
        key: "bk" + obj.bookId,
        success: function(res) {
            wx.showLoading({
                title: "正在加载...",
                mask: true
            });
            var bookData = res.data;
            for (var i = 0; i < bookData.length; i++) {
                if (obj.chapterId == bookData[i].chapterId) {
                    content = bookData[i].content;
                    console.log("缓存读取" + obj.bookName + "第" + obj.chapterId + "章");
                    wx.navigateTo({
                        url: '../content/content' + '?bookName=' + obj.bookName + '&chapterId=' + obj.chapterId + '&chapterCount=' + obj.chapterCount + '&bookId=' + obj.bookId + '&content=' + content + '&lid=' + obj.verseid + '&from=3',
                        success: function(res) {
                            wx.hideLoading();
                            // success
                        },
                        fail: function() {
                            wx.hideLoading();
                            // fail
                        }
                    })
                }
            }
        },
        fail: function() {
            wx.showLoading({
                title: "首次加载该卷",
                mask: true
            });
            wx.request({
                url: glo.https + '/chapter/list_bookid?bookId=' + obj.bookId,
                method: 'GET',
                header: {
                    'Content-Type': 'application/json'
                },
                success: function(res) {
                    wx.setStorage({ //添加缓存
                        key: "bk" + obj.bookId,
                        data: res.data
                    });
                    var bookData = res.data;
                    console.log()
                    for (var i = 0; i < bookData.length; i++) {
                        if (obj.chapterId == bookData[i].chapterId) {
                            content = bookData[i].content;
                            console.log("缓存读取" + obj.bookName + "第" + obj.chapterId + "章");
                            wx.navigateTo({
                                url: '../content/content' + '?bookName=' + obj.bookName + '&chapterId=' + obj.chapterId + '&chapterCount=' + obj.chapterCount + '&bookId=' + obj.bookId + '&content=' + content + '&lid=' + obj.verseid + '&from=3',
                                success: function(res) {
                                    wx.hideLoading();
                                    // success
                                },
                                fail: function() {
                                    wx.hideLoading();
                                    wx.showToast({
                                        title: '加载失败，请检查网络',
                                        icon: 'loading',
                                        duration: 1000
                                    })
                                    // fail
                                }
                            })
                        }
                    }
                }
            })
        }
    });
}
Page({
    data: {
        wxgrid: {},
        wxgridNew: {},
        winWidth: 0,
        winHeight: 0,
        // tab切换  
        currentTab: 0,
        tabNum: 0,
        bibleNum: 0,
        bookList: [],
        opa: "display:none",
        searchTip: '搜索菜谱',
        oldMenu: '黑暗料理',
        newMenu: "",
        biblename: '菜谱',
        pageEnable: false,
        pageEnable2: true,
        pageEnable1: true,
        isCurrbook: true,
        currChapter: 3,
        url: "../../pages/list/list",
        items: [{
                text: "美容",
                src: "../../images/menu/mr.png"
            },
            {
                text: "减肥",
                src: "../../images/menu/jf.png"
            },
            {
                text: "养生",
                src: "../../images/menu/ys.png"
            },
            {
                text: "全菜系",
                src: "../../images/menu/qcx.png"
            },
            {
                text: "消化",
                src: "../../images/menu/xh.png"
            },
            {
                text: "家常",
                src: "../../images/menu/jc.png"
            },
            {
                text: "孕妇",
                src: "../../images/menu/rf.png"
            },
            {
                text: "清热解暑",
                src: "../../images/menu/qrjd.png"
            },
            {
                text: "快手菜",
                src: "../../images/menu/ksc.png"
            },
            {
                text: "去火",
                src: "../../images/menu/quh.png"
            },
            {
                text: "素食",
                src: "../../images/menu/ss.png"
            },
            {
                text: "老人",
                src: "../../images/menu/lr.png"
            },
            {
                text: "清肺",
                src: "../../images/menu/qf.png"
            },
            {
                text: "凉菜",
                src: "../../images/menu/lc.png"
            },
            {
                text: "饮品",
                src: "../../images/menu/yp.png"
            },
            {
                text: "增肥",
                src: "../../images/menu/zf.png"
            },
            {
                text: "补钙",
                src: "../../images/menu/bg.png"
            },
            {
                text: "川菜",
                src: "../../images/menu/cc.png"
            },
            {
                text: "青少年",
                src: "../../images/menu/qsl.png"
            },
            {
                text: "祛寒",
                src: "../../images/menu/qh.png"
            },
            {
                text: "海鲜",
                src: "../../images/menu/hx.png"
            },
        ]
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var bibleNum = this.data.bibleNum;
        var bookList = [];
        // var currentTime = new Date().getTime();
        // var nowDate = new Date(glo.fbtime);
        var that = this;
        // bibleData.reLoadBible();
        if (bibleNum !== 0) {
            bookList = wx.getStorageSync('bibleRead')[bibleNum - 1];

            if (bookList !== undefined) {
                bookList.shift();
            }
            that.setData({
                bookList: bookList
            });
        }


        // if (glo.validBible()) {
        //   var v = "%E5%9C%A3%E7%BB%8F"
        //   var o = "%E6%97%A7%E7%BA%A6"
        //   var n = "%E6%96%B0%E7%BA%A6"
        //   var k = "%E8%BE%93%E5%85%A5%E5%9C%A3%E7%BB%8F%E7%BB%8F%E6%96%87"
        //   wx.setNavigationBarTitle({
        //     title: decodeURI(v),
        //   })
        //   that.setData({
        //     oldMenu: decodeURI(o),
        //     newMenu: decodeURI(n),
        //     searchTip: decodeURI(k),
        //     pageEnable: true,
        //     biblename: decodeURI(v)
        //   });
        // }
        // else{
        //   wx.setNavigationBarTitle({
        //     title: '我家菜谱',
        //   })
        // }
        // that.loadBibleV(that.loadCatalog);

        that.loadCatalog();
        // var that = this;
        var lastread = wx.getStorageSync("lastread");
        var arr00 = lastread.split("-");
        if (lastread != "") {

            var bookId = arr00[0];
            var chapterId = arr00[1];
            var bookName = arr00[2];
            var chapterCount = arr00[3];
            var verseId = arr00[4];
            var isCurrbook1 = that.data.isCurrbook;
            if (bibleMsg.bookId == bookId) {
                isCurrbook1 = true;
            } else {
                isCurrbook1 = false;
            }
            // var self = this;
            lastread = bookName + "第" + chapterId + "章";
            that.setData({
                bookId: bookId,
                chapterId: chapterId,
                bookName: bookName,
                chapterCount: chapterCount,
                verseId: verseId,
                lastread: lastread,
                opa: "opacity:1",
                isCurrbook: isCurrbook1,
                currChapter: chapterId
            });
        }

        // wx.getNetworkType({
        //   success: function(res) {
        //     // 返回网络类型, 有效值：
        //     // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        //     var networkType = res.networkType
        //     if (networkType == "wifi") { //wifi 下直接更新
        //       glo.wifiUpdateBibleData(null);
        //     }
        //   }
        // });
    },

    urlHistory: function() {
        wx.navigateTo({
            url: '../message/message',
        })
    },
    urlSearch: function() {
        //url: '../search/search',
        wx.navigateTo({
            url: '../search/search',
        })
    },
    nearReadTap: function(e) {
        // var currentTime = new Date().getTime();
        // var nowDate = new Date(glo.fbtime);
        var self = this;
        // if ((currentTime - nowDate.getTime()) > 0) {
        //   console.log(e)
        var curTime = e.timeStamp;
        var lastTime = lastTapDiffTime;
        if (lastTime > 0) {
            if (curTime - lastTime < 300) {
                console.log("双击事件");
                lastTapDiffTime = curTime;
                return;
            }
        }

        lastTapDiffTime = curTime;

        var bookId = e.target.dataset.bookid;
        var chapterId = e.target.dataset.chapterid;
        var bookName = e.target.dataset.bookname;
        var chapterCount = e.target.dataset.chaptercount;
        var verseid = e.target.dataset.verseid;
        var content = "";
        var keyid = "CH" + "-" + bookId + "-" + chapterId;

        wx.getStorage({
            key: "bk" + bookId,
            success: function(res) {
                wx.showLoading({
                    title: "正在加载...",
                    mask: true
                });
                var bookData = res.data;
                for (var i = 0; i < bookData.length; i++) {
                    if (chapterId == bookData[i].chapterId) {
                        content = bookData[i].content;
                        console.log("缓存读取" + bookName + "第" + chapterId + "章");
                        wx.navigateTo({
                            url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid + '&from=3',
                            success: function(res) {
                                wx.hideLoading();
                                // success
                            },
                            fail: function() {
                                wx.hideLoading();
                                // fail
                            }
                        })
                    }
                }
            },
            fail: function() {
                wx.showLoading({
                    title: "首次加载该卷",
                    mask: true
                });
                wx.request({
                    url: glo.https + '/chapter/list_bookid?bookId=' + bookId,
                    method: 'GET',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: function(res) {
                        wx.setStorage({ //添加缓存
                            key: "bk" + bookId,
                            data: res.data
                        });
                        var bookData = res.data;
                        for (var i = 0; i < bookData.length; i++) {
                            if (chapterId == bookData[i].chapterId) {
                                content = bookData[i].content;
                                console.log("缓存读取" + bookName + "第" + chapterId + "章");
                                wx.navigateTo({
                                    url: '../content/content' + '?bookName=' + bookName + '&chapterId=' + chapterId + '&chapterCount=' + chapterCount + '&bookId=' + bookId + '&content=' + content + '&lid=' + verseid + '&from=3',
                                    success: function(res) {
                                        wx.hideLoading();
                                        // success
                                    },
                                    fail: function() {
                                        wx.hideLoading();
                                        wx.showToast({
                                            title: '加载失败，请检查网络',
                                            icon: 'loading',
                                            duration: 1000
                                        })
                                        // fail
                                    }
                                })
                            }
                        }
                    }
                })
            }
        });
        // } else {
        //   wx.showToast({
        //     title: '正在加载.....',
        //   });
        // }

    },
    bibleList: function(e) {
        // var currentTime = new Date().getTime();
        // var nowDate = new Date(glo.fbtime);
        var that = this;
        var dataset = e.currentTarget.dataset;
        var bibleNum = dataset.bookid; //卷编号
        var isCurrbook1 = that.data.isCurrbook;
        if (that.data.pageEnable) {
            var bookList = [];
            if (this.data.bibleNum == bibleNum) { //隐藏
                bibleNum = 0
            } else { //展开    
                bookList = wx.getStorageSync('bibleRead')[bibleNum - 1];
                if (bookList !== undefined) {
                    bookList.shift();
                }
                console.log(bookList)
                app.getUserInfo(function(userInfo) { //改

                });
                //  else {
                //   // wx.navigateTo({
                //   //   url: '../authorize/authorize',
                //   // })      
                // }

                bibleMsg.bookId = bibleNum;
                bibleMsg.bookName = dataset.bookname;
                bibleMsg.chapterCount = dataset.bookchaptercount;

                var bookId = that.data.bookId
                if (bibleMsg.bookId == bookId) {
                    isCurrbook1 = true;
                } else {
                    isCurrbook1 = false;
                }

            }
            this.setData({
                tabNum: dataset.tabnum,
                bibleNum: bibleNum,
                bookList: bookList,
                isCurrbook: isCurrbook1
            });



        } else {
            wx.navigateTo({
                url: '../Menus/Menus' + '?bookId=' + bibleNum,
            })
            // wx.showToast({
            //   title: '正在加载.....',
            // });
        }


    },
    catalogUrl: function(e) {
        bibleMsg.chapterId = e.currentTarget.dataset.listnum;
        this.setData({
            currChapter: bibleMsg.chapterId,
            isCurrbook: true
        })
        _goContent(bibleMsg);
    },
    loadPersonal: function() {
        var that = this;
        // that.setData({ currentTab: 1 });
        wx.getSetting({
            success: function(res) {
                if (res.authSetting['scope.userInfo'] || 1 == 1) { //改
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    app.getUserInfo(function(userInfo) {
                        var bibleRead = glo.punchCalcLastYear(userInfo.punch);
                        wx.setStorageSync('bibleRead', bibleRead);
                        /* for (var i = 0; i < 66; i++) {
                           if (i < 39) {
                             if (bibleRead[i][0] == -1) {
                               bibleData.oldbooks[i].flag = "c";
                               bibleData.oldbooks[i].readCount = 0;
                             } else if (bibleRead[i][0] == 0) {
                               bibleData.oldbooks[i].flag = "b";
                               bibleData.oldbooks[i].readCount = 0;
                             } else {
                               bibleData.oldbooks[i].flag = "a";
                               bibleData.oldbooks[i].readCount = bibleRead[i][0];
                             }
                           } else {
                             if (bibleRead[i][0] == -1) {
                               bibleData.newbooks[i - 39].flag = "c";
                               bibleData.newbooks[i - 39].readCount = 0;
                             } else if (bibleRead[i][0] == 0) {
                               bibleData.newbooks[i - 39].flag = "b";
                               bibleData.newbooks[i - 39].readCount = 0;
                             } else {
                               bibleData.newbooks[i - 39].flag = "a";
                               bibleData.newbooks[i - 39].readCount = bibleRead[i][0];
                             }
                           }
                         }*/

                        // wx.request({
                        //   url: glo.https + '/person/getmsg?userid=' + userInfo.userId,
                        //   method: 'GET',
                        //   header: {
                        //     'Content-Type': 'application/json'
                        //   },
                        //   success: function(res) {

                        //     var msgs = res.data;
                        //     for (var i = 0; i < msgs.length; i++) {

                        //       var msg = msgs[i];
                        //       wx.navigateTo({
                        //         url: '../notice/notice' + '?nickname=' + userInfo.nickName + '&msg=' + msg.content,
                        //         success: function(res) {
                        //           wx.hideLoading();
                        //           // success
                        //         },
                        //         fail: function() {
                        //           wx.hideLoading();
                        //           wx.showToast({
                        //             title: '加载失败，请检查网络',
                        //             icon: 'loading',
                        //             duration: 1000
                        //           })
                        //           // fail
                        //         }
                        //       })
                        //       // wx.showToast({
                        //       //   title: msg.content,
                        //       //   icon: 'loading',
                        //       //   duration: 2000
                        //       // })

                        //     }

                        //   }
                        // })

                    });
                } else {
                    // wx.navigateTo({
                    //   url: '../authorize/authorize',
                    // })
                }
            }
        });
    },

    loadBibleV: function(ff) {
        var that = this;
        wx.request({
            url: glo.https + '/conf/getval?mkey=' + glo.enablev,
            method: 'GET',
            success: function(res0) {
                var enablev = res0.data;
                wx.setStorage({
                    key: glo.enablev,
                    data: enablev,
                    success: function() {
                        bibleData.reLoadBible();
                        ff();
                    }
                })

                //  wx.setStorageSync('enablev', enablev);

            },
            fail: function() {
                wx.setStorageSync(glo.enablev, '0');
                bibleData.reLoadBible();
                wx.hideLoading();
                ff();
            }

        })
    },

    loadCatalog: function() {
        console.log('fffffffffffffff')
        var that = this;
        // that.setData({ currentTab: 1 });
        var wxgrid1 = new WXGrid;
        wxgrid1.init(13, 3);
        var wxgrid2 = new WXGrid;
        wxgrid2.init(9, 3);
        if (bibleData.oldbooks == undefined) {
            return;
        }
        wxgrid1.data.add("classifies", bibleData.oldbooks);
        wxgrid2.data.add("classifies", bibleData.newbooks);
        console.log(wxgrid1)
        console.log(wxgrid2)
        var res = wx.getSystemInfoSync();
        var panelHeight = res.windowHeight - res.windowWidth / 750 * 80
        console.debug("h px" + res.windowWidth / 750 * 100);
        if (res.platform == "android") {
            if (res.windowWidth >= 360) {
                panelHeight = 462;
            } else {
                panelHeight = 396;
            }
        }
        that.setData({
            wxgrid: wxgrid1,
            wxgridNew: wxgrid2,
            winHeight: panelHeight
        });
        that.loadPersonal();
    },
    onLoad: function() {
        //bibleData.reLoadBible();
        wx.getStorage({
            key: 'lastread',
            success: function(res) {
                console.log(res)
            }
        });

        var that = this;
        that.setData({
            currentTab: 1
        });


        var preloadFun = function() {
            if (glo.validBible()) {
                var v = "%E5%9C%A3%E7%BB%8F"
                var o = "%E6%97%A7%E7%BA%A6"
                var n = "%E6%96%B0%E7%BA%A6"
                var k = "%E8%BE%93%E5%85%A5%E5%9C%A3%E7%BB%8F%E7%BB%8F%E6%96%87"
                wx.setNavigationBarTitle({
                    title: config.btitle, //decodeURI(v),
                })
                that.setData({
                    oldMenu: decodeURI(o),
                    newMenu: decodeURI(n),
                    searchTip: decodeURI(k),
                    pageEnable: true,
                    pageEnable1: true,
                    pageEnable2: true,
                    biblename: decodeURI(v)
                });
            } else {
                that.setData({
                    newMenu: '经典家常菜',
                    pageEnable1: false,
                    pageEnable2: false,
                });
                wx.setNavigationBarTitle({
                    title: '菜谱合本',
                })
            }
            that.loadCatalog();
        }

        that.loadBibleV(preloadFun);
    },


    /** 
     * 滑动切换tab 
     */
    bindChange: function(e) {
        var that = this;
        that.setData({
            currentTab: e.detail.current,
            bibleNum: 0
        });

    },
    /**
     * 用户点击右上角
     */
    onShareAppMessage: function() {
        var v = "菜单";
        if (this.data.pageEnable) {
            v = "%E5%9C%A3%E7%BB%8F"
            v = decodeURI(v)
        }
        return {

            title: ' 这是一款免下载的小程序' + v + ',点开即可马上使用！',

            desc: '微信小程序版本' + v,

            path: '/pages/index/index'

        }
    },
    /** 
     * 点击tab切换 
     */
    swichNav: function(e) {
        var that = this;

        if (this.data.currentTab === e.target.dataset.current) {
            return false;
        } else {
            that.setData({
                currentTab: e.target.dataset.current,
                bibleNum: 0
            })
        }
    }

})